<template>
  <div class="app-container">

    <div class="xsDiv">
      <div>
      <el-image src="sl.png" class="slImg"></el-image>
      <div class="jkslDiv">报修总数<br><span class="jkwzSpan">{{this.repair.repairSumCount}}</span></div>
      </div>
      <div id="echat1" class="echat1"></div>
    </div>

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="70px">
      <el-form-item label="工单编号" prop="repairOrderNo">
        <el-input v-model="queryParams.repairOrderNo" class="form-group" placeholder="请输入工单编号" size="small"/>
      </el-form-item>
      <el-form-item label="报修分类" prop="repairType">
        <el-select v-model="queryParams.repairType" placeholder="请选择报修分类" clearable size="small">
          <el-option label="个人报修" value="1" />
          <el-option label="公共报修" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="报修状态" prop="repairStatus">
        <el-select v-model="queryParams.repairStatus" placeholder="请选择报修状态" clearable size="small">
          <el-option label="已指派" value="1" />
          <el-option label="已受理" value="2" />
          <el-option label="已处理" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="报修时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 400px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList"  @selection-change="handleSelectionChange">
      <el-table-column label="序号"  type="index" align="center" />
      <el-table-column label="工单编号" align="center" prop="repairOrderNo" show-overflow-tooltip/>
      <el-table-column label="报修分类" align="center" prop="repairType" >
        <template slot-scope="scope">
          <span v-if="scope.row.repairType == 1">个人报修</span>
          <span v-else>公共报修</span>
        </template>
      </el-table-column>
      <el-table-column label="报修人" align="center" prop="repairPeopleName" />
      <el-table-column label="报修内容" align="center" prop="repairContent" show-overflow-tooltip/>
      <el-table-column label="报修地址" align="center" prop="repairAddress" show-overflow-tooltip/>
      <el-table-column label="关联设备" align="center" prop="repairDeviceName" show-overflow-tooltip/>
      <el-table-column label="联系电话" align="center" prop="mobile" width="120px"/>
      <el-table-column label="报修时间" align="center" prop="repairTime" show-overflow-tooltip/>
      <el-table-column label="工单时效" align="center" prop="repairOnTime"/>
      <el-table-column label="指派人员" align="center" prop="repairAppointName" />
      <el-table-column label="报修状态" align="center" prop="repairStatus" >
        <template slot-scope="scope">
          <span v-if="scope.row.repairStatus == 1">已指派</span>
          <span v-else-if="scope.row.repairStatus == 2">已受理</span>
          <span v-else>已处理</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding" width="180px">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.repairStatus < 2"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-if="scope.row.repairStatus < 2"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            v-if="scope.row.repairStatus < 2"
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="changeAppoint(scope.row.id)"
          >改派</el-button>
          <el-button
            v-if="scope.row.repairStatus == 2"
            size="mini"
            type="text"
            icon="el-icon-chat-dot-round"
            @click="urged(scope.row)"
          >催处</el-button>
          <el-button
            v-if="scope.row.repairStatus == 3"
            size="mini"
            type="text"
            @click="detailRepair(scope.row)"
          >处理详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改评论对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" :before-close="cancel" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="报修分类" prop="repairType">
          <el-select v-model="form.repairType" placeholder="请选择报修分类">
            <el-option label="个人报修" value="1" />
            <el-option label="公共报修" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="报修内容" prop="repairContent">
          <el-input v-model="form.repairContent" type="textarea" placeholder="请输入报修内容" />
        </el-form-item>
        <el-form-item label="报修地址" prop="repairAddress">
          <el-input v-model="form.repairAddress" type="textarea" placeholder="请输入报修地址" />
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item  label="选择设备">
          <el-input v-model="form.repairDeviceName" disabled class="form-group">
            <el-button slot="append" icon="el-icon-search" @click="selectDevice" />
          </el-input>
        </el-form-item>
        <el-form-item  label="指派人员">
          <el-input v-model="form.repairAppointName" disabled class="form-group">
            <el-button slot="append" icon="el-icon-search" @click="findUser" />
          </el-input>
        </el-form-item>
        <el-form-item label="工单时效" prop="repairOnTime">
          <el-input v-model="form.repairOnTime" type="number" placeholder="请输入工单时效(小时)" />
        </el-form-item>
        <el-form-item label="上传照片">
          <el-upload
            action="#"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :http-request="uploadAvatar"
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <find-user :title="userCtr.title" :visible="userCtr.visible" @close-callback="userCloseCallback" />
    <change-appoint :title="appointCtr.title" :visible="appointCtr.visible" :id="appointCtr.id" @close-callback="appointCloseCallback"/>
    <select-device :title="deviceCtr.title" :visible="deviceCtr.visible "  @close-callback="deviceCloseCallback"/>
    <repair-resolve-detail :title="detailCtr.title" :visible="detailCtr.visible" :repairOrderNo="detailCtr.repairOrderNo" @close-callback="detailCloseCallback"/>
  </div>
</template>

<script>
import { listRepair, getRepair, delRepair, addRepair, updateRepair,getRepairData,uploadImg } from "@/api/system/repair";
import { addSysMsg } from "@/api/system/msg";
import  RepairResolveDetail from '@/views/system/repair/repairResolveDetail/index'
import FindUser from '@/views/system/repair/user/findUser'
import ChangeAppoint from '@/views/system/repair/changeAppoint/index'
import SelectDevice from '@/views/system/repair/selectDevice/index'
import echarts from "echarts";

export default {
  name: "Repair",
  components: { FindUser,ChangeAppoint,SelectDevice,RepairResolveDetail },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      picList: [],
      fileList: [],
      imgUrlList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      imgViewUrl:"",
      dateRange:[],
      // 评论表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        repairType: null,
        repairPeople: null,
        repairContent: null,
        repairAddress: null,
        mobile: null,
        repairTime: null,
        repairAppoint: null,
        repairStatus: null
      },
      userCtr: {
        title: '选择维修人员',
        visible: false
      },
      appointCtr: {
        title: '改派',
        visible: false,
        id:0
      },
      deviceCtr:{
        title: '选择设备',
        visible: false,
      },
      detailCtr:{
        title:'处理详情',
        visible:false,
        repairOrderNo:null
      },
      repair:{},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        repairType:  [
          {required: true, message: '请选择报修分类', trigger: ['blur','change']}
        ],
        repairContent: [
          {required: true, message: '请填写报修内容', trigger: ['blur','change']}
        ],
        repairAddress:  [
          {required: true, message: '请填写报修地址', trigger: ['blur','change']}
        ],
        mobile: [
          {required: true, message: '请填写联系电话', trigger: ['blur','change']}
        ],
        repairOnTime: [
          {required: true, message: '请填写工单时效', trigger: ['blur','change']}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    uploadAvatar(item) {
      console.log(item)
      const formData = new FormData()
      formData.append('uploadFile', item.file)
      const uid = item.file.uid
      uploadImg(formData).then(res => {
        this.picList.push({ key: uid, value: res.data.id})
        this.emptyUpload()
      }).catch(() => {
        this.$message.error('上传失败，请重新上传')
        this.emptyUpload()
      })
    },
    handleRemove(file, fileList) {
      for (const i in this.picList) {
        if (this.picList[i].key === file.uid) {
          this.picList.splice(i, 1)
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /**
     * 清空上传组件
     */
    emptyUpload() {
      const mainImg = this.$refs.upload
      if (mainImg) {
        if (mainImg.length) {
          mainImg.forEach(item => {
            item.clearFiles()
          })
        } else {
          this.$refs.upload.clearFiles()
        }
      }
    },
    /** 查询报修列表 */
    getList() {
      this.loading = true;
      listRepair(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;

        this.getRepairData();
      });
    },
    getRepairData(){
      getRepairData().then(res => {
        this.repair = res.data
        this.drawPie()
      })
    },
    //催处操作
    urged(row){
      addSysMsg({
        msgTitle:"故障报修催处",
        msgText:"请你尽快处理【"+row.repairPeopleName+"】的故障报修，谢谢配合！",
        userNos:row.repairAppoint,
        isTimeSend:0
      }).then( res => {
          if (res.code === 200){
            this.msgSuccess("催处成功");
          }else{
            this.msgSuccess("催处失败");
          }
      })
    },
    /** 处理详情按钮 */
    detailRepair(row) {
      this.reset();
      this.detailCtr.visible = true
      this.detailCtr.repairOrderNo = row.repairOrderNo
    },
    detailCloseCallback(){
      this.detailCtr.visible = false
      this.detailCtr.repairOrderNo = null
    },
    findUser() {
      this.userCtr.visible = true;
    },
    selectDevice(){
      this.deviceCtr.visible = true;
    },
    changeAppoint(id){
      this.appointCtr.visible = true;
      this.appointCtr.id = id;
    },
    userCloseCallback(checkUserNos, checkNicknames) {
      this.userCtr.visible = false;
      this.form.repairAppointName = checkNicknames;
      this.form.repairAppoint = checkUserNos;
    },
    appointCloseCallback(){
      this.appointCtr.visible = false
      this.getList()
    },
    deviceCloseCallback(deviceNo,deviceName){
      this.deviceCtr.visible = false
      this.form.repairDeviceNo = deviceNo;
      this.form.repairDeviceName = deviceName;
    },
    drawPie() {
      const charts = echarts.init(document.getElementById('echat1'));
      var option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 350,
          top: 60,
          itemWidth: 10,//图例颜色块的宽度和高度
          itemHeight: 10,
          data: ['已指派', '已受理','已处理']
        },
        color: ['#3ad0fe','#ffd86e','#9f55cd'],
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: ['60%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '25',
                fontWeight: 'bold',
                formatter: '{d}%'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              {value: this.repair.appointCount, name: '已指派'},
              {value: this.repair.acceptCount, name: '已受理'},
              {value: this.repair.dealCount, name: '已处理'}
            ]
          }
        ]
      }
      charts.setOption(option);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.emptyUpload()
      this.fileList = []
      this.picList = []
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        repairType: null,
        repairPeople: null,
        repairContent: null,
        repairAddress: null,
        mobile: null,
        repairTime: null,
        repairAppoint: null,
        repairStatus: null,
        repairImg: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange=[];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报修";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRepair(id).then(response => {
        this.form = response.data;
        this.form.repairType = this.form.repairType + ''
        if (this.form.repairImg != null && this.form.repairImg != ""){
           this.imgUrlList = this.form.repairImg.split(",")
          for (let i = 0; i <this.imgUrlList.length; i++) {
            this.picList.push({ key: i+1, value: this.imgUrlList[i]})
            this.fileList.push({uid:i+1,url:this.$store.state.file.viewPath+this.imgUrlList[i]})
          }
        }
        this.open = true;
        this.title = "修改报修";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.repairAppointName == null){
            this.$message({
              message: '请选择指派人员',
              type: 'warning'
            });
            return;
          }
          let urlList = this.picList.map( n => n.value);
          let fileUrl = urlList.join(",");
          this.form.repairImg = fileUrl
          if (this.form.id != null) {
            updateRepair(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                this.emptyUpload()
                this.fileList = []
                this.picList = []
              }
            });
          } else {
            addRepair(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                this.emptyUpload()
                this.fileList = []
                this.picList = []
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除评论编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRepair(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/repair/export', {
        ...this.queryParams
      }, `system_repair.xlsx`)
    }
  }
};
</script>

<style  lang="scss" scoped>
.xsDiv{width: 100%;height: 200px;border: #dbd9d9 1px solid;margin-bottom: 30px;display: flex;justify-content: space-around;}
  .slImg{margin: 50px 0 0 150px;}
  .jkslDiv{margin: -90px 0 0 280px;display: block;color: #9a9a9e;}
  .jkwzSpan{margin: 20px 0 0 0;color: #1e1e1e;font-size: 40px;display: inline-block;}
  .echat1{width: 500px;height: 200px;margin: 0 0 0 200px;}
</style>
